package main

import (
	"fmt"
	"image"
	"image/color"
	"image/gif"
	"io"
	"math"
	"net/http"
	"os"
)

const (
	size    = 128
	nframes = 100
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		lissajous(w)
	})

	err := http.ListenAndServe(":8001", nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
	}
}

func lissajous(w io.Writer) {
	p := 1.0
	q := 2.0
	phi := 0.0

	palett := []color.Color{color.RGBA{0xee, 0xee, 0xee, 0xff}, color.RGBA{0xff, 0, 0, 0xff}}
	rec := image.Rect(0, 0, 2*size, 2*size)

	s := float64(size - 10)

	step := 0.01
	// 生成 100 帧
	anim := gif.GIF{LoopCount: 0}
	for frames := 0; frames < nframes; frames++ {
		img := image.NewPaletted(rec, palett)
		for t := -2 * math.Pi; t <= 2*math.Pi; t += 0.0001 {
			x := math.Sin(p * t)
			y := math.Sin(q*t + phi)
			img.SetColorIndex(size+int(s*x+0.5), size+int(s*y+0.5), 1)
		}
		anim.Image = append(anim.Image, img)
		anim.Delay = append(anim.Delay, 10)
		// 每一帧 q 递增 0.01，这里相当于 q/p 以 0.01 步长递增
		p += step
	}

	gif.EncodeAll(w, &anim)
}
